<template>
  <div class="article-container">
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh" :success-text="successText" success-duration="3000">
        <van-list
  v-model="loading"
  :finished="finished"
  finished-text="没有更多了"
  :error.sync="error"
  error-text="请求失败，点击重新加载"
  @load="onLoad"
>
  <!-- <van-cell v-for="(item,index) in list" :key="index" :title="item.title" /> -->
  <article-Item v-for="(item,index) in list" :key="index"   :articles="item"></article-Item>
</van-list>
        </van-pull-refresh>

  </div>
</template>

<script>
import { getArticleListAPI } from '../../../api/index.js'
import articleItem from '../../../components/article-item.vue'
export default {
  name: 'articlePage',
  props: {
    channels: {
      type: Object,
      default: () => ({})
    }
  },
  components: { articleItem },
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      error: false,
      timestamp: '', // 请求下一页的时间戳
      refreshing: false,
      successText: '' // 下拉刷新完成提示
    }
  },
  methods: {
    async onLoad () { // 自动加载列表数据
      try {
        // 犯错实例代码：主动犯错，让try中的逻辑报错
        // if (Math.random() < 0.6) {
        //   JSON.parse('WWW')
        // }

        const res = await getArticleListAPI({
          channel_id: this.channels.id,
          timestamp: this.timestamp || Date.now()
        })
        console.log(res)
        // 2
        this.list.push(...res.data.data.results)
        this.loading = false
        if (res.data.data.results.length === 0) {
          this.finished = true
        } else {
          this.timestamp = res.data.data.pre_timestamp
        }
      } catch (error) {
        this.loading = false// 请求失败关闭加载状态
        this.error = true// 请求失败弹出报错
      }

      // 异步更新数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      //   setTimeout(() => {
      //     for (let i = 0; i < 10; i++) {
      //       this.list.push(this.list.length + 1)
      //     }

      //     // 加载状态结束
      //     this.loading = false

    //     // 数据全部加载完成
    //     if (this.list.length >= 40) {
    //       // 如果没有数据了，把finished设置成true,之后就不会触发@loads事件了
    //       this.finished = true
    //     }
    //   }, 1000)
    },
    async onRefresh () { // 下拉刷新数据
      try {
        const res = await getArticleListAPI({
          channel_id: this.channels.id,
          timestamp: this.timestamp
        })
        this.list.unshift(...res.data.data.results)
        this.refreshing = false
        this.successText = `刷新成功，更新了${res.data.data.results.length}条数据`
      } catch (error) {
        this.refreshing = false
        this.successText = '刷新失败'
      }
    }
  }
}
</script>

<style lang="less" scoped>
.article-container{
height:79vh;//如何计算一个盒子应该有的视口高度：总视口高度减去（顶部导航的高度加底部导航的高度-频道列表的高度）/视口的高度。因为再次之前视口滚动是body滚动
overflow-y:auto;
}
</style>
